
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Tathata.Common.BLL.Entities;
using Tathata.Common.BLL.Managers;
using Tathata.Common.Utils;
using System.Collections.Generic;
using Tathata.Common.BLL.EntityCollections;
using Tathata.Web.Administration.Modules;
namespace Tathata.Web.Administration
{
    public partial class Administration_ProductDetails : BaseNopAdministrationPage
    {
        private void BindData()
        {
            Product product = ProductManager.GetByProductID(this.ProductID);
            if (product != null)
            {
                this.txtName.Text = product.Name;
                this.txtShortDescription.Text = product.ShortDescription;
                this.txtFullDescription.Value = product.FullDescription;
                this.txtAdminComment.Text = product.AdminComment;
                CommonHelper.SelectListItem(this.ddlProductType, product.ProductTypeID);
                CommonHelper.SelectListItem(this.ddlTemplate, product.TemplateID);
                this.txtMetaKeywords.Text = product.MetaKeywords;
                this.txtMetaDescription.Text = product.MetaDescription;
                this.txtMetaTitle.Text = product.MetaTitle;
                this.txtSEName.Text = product.SEName;
                this.cbAllowCustomerReviews.Checked = product.AllowCustomerReviews;
                this.cbPublished.Checked = product.Published;

                ProductReviewCollection productReviews = product.ProductReviews;
                if (productReviews.Count > 0)
                {
                    hlViewReviews.Visible = true;
                    hlViewReviews.Text = "View Reviews (" + productReviews.Count.ToString() + ")";
                    hlViewReviews.NavigateUrl = "ProductReviews.aspx?ProductID=" + product.ProductID.ToString();
                }
                else
                    hlViewReviews.Visible = false;


                ProductCategoryCollection existingProductCategoryCollection = product.ProductCategories;
                List<ProductCategoryMappingHelperClass> productCategoryMappings = GetProductCategoryMappings(0, string.Empty, existingProductCategoryCollection);
                gvCategoryMappings.DataSource = productCategoryMappings;
                gvCategoryMappings.DataBind();

                ProductManufacturerCollection existingProductManufacturerCollection = product.ProductManufacturers;
                List<ProductManufacturerMappingHelperClass> productManufacturerMappings = GetProductManufacturerMappings(existingProductManufacturerCollection);
                gvManufacturerMappings.DataSource = productManufacturerMappings;
                gvManufacturerMappings.DataBind();

                RelatedProductCollection existingRelatedProductCollection = product.RelatedProducts;
                List<RelatedProductHelperClass> relatedProducts = GetRelatedProducts(existingRelatedProductCollection);
                gvRelatedProducts.DataSource = relatedProducts;
                gvRelatedProducts.DataBind();

                BindPictures();
            }
            else
                Response.Redirect("Products.aspx");
        }

        private void BindPictures()
        {
            ProductPictureCollection productPictures = ProductPictureManager.GetAllByProductID(this.ProductID);
            if (productPictures.Count > 0)
            {
                gvwImages.Visible = true;
                gvwImages.DataSource = productPictures;
                gvwImages.DataBind();                
            }
            else
                gvwImages.Visible = false;
        }

       

        private void FillDropDowns()
        {
            this.ddlTemplate.Items.Clear();
            ProductTemplateCollection productTemplateCollection = ProductTemplateManager.GetAllProductTemplates();
            foreach (ProductTemplate productTemplate in productTemplateCollection)
            {
                ListItem item2 = new ListItem(productTemplate.Name, productTemplate.ProductTemplateID.ToString());
                this.ddlTemplate.Items.Add(item2);
            }

            this.ddlProductType.Items.Clear();
            ProductTypeCollection productTypeCollection = ProductTypeManager.GetAllProductTypes();
            foreach (ProductType productType in productTypeCollection)
            {
                ListItem item2 = new ListItem(productType.Name, productType.ProductTypeID.ToString());
                this.ddlProductType.Items.Add(item2);
            }
        }
      
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.FillDropDowns();
                this.BindData();
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    Product product = ProductManager.GetByProductID(this.ProductID);
                    if (product != null)
                    {
                        product = ProductManager.UpdateProduct(this.ProductID, txtName.Text, txtShortDescription.Text, txtFullDescription.Value, txtAdminComment.Text,
                             int.Parse(this.ddlProductType.SelectedItem.Value), int.Parse(this.ddlTemplate.SelectedItem.Value),
                             txtMetaKeywords.Text, txtMetaDescription.Text, txtMetaTitle.Text, txtSEName.Text, cbAllowCustomerReviews.Checked,
                             product.RatingSum, product.TotalRatingVotes, cbPublished.Checked, product.Deleted, product.CreatedOn, DateTime.Now);

                        foreach (GridViewRow row in gvCategoryMappings.Rows)
                        {
                            CheckBox cbCategoryInfo = row.FindControl("cbCategoryInfo") as CheckBox;
                            HiddenField hfCategoryID = row.FindControl("hfCategoryID") as HiddenField;
                            HiddenField hfProductCategoryID = row.FindControl("hfProductCategoryID") as HiddenField;
                            CheckBox cbFeatured = row.FindControl("cbFeatured") as CheckBox;
                            NumericTextBox txtRowDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox;
                            int productCategoryID = int.Parse(hfProductCategoryID.Value);
                            int categoryID = int.Parse(hfCategoryID.Value);
                            int displayOrder = txtRowDisplayOrder.Value;

                            if (productCategoryID > 0 && !cbCategoryInfo.Checked)
                                ProductCategoryManager.DeleteProductCategory(productCategoryID);
                            if (productCategoryID > 0 && cbCategoryInfo.Checked)
                                ProductCategoryManager.UpdateProductCategory(productCategoryID, product.ProductID, categoryID, cbFeatured.Checked, displayOrder);
                            if (productCategoryID == 0 && cbCategoryInfo.Checked)
                                ProductCategoryManager.InsertProductCategory(product.ProductID, categoryID, cbFeatured.Checked, displayOrder);
                        }

                        foreach (GridViewRow row in gvManufacturerMappings.Rows)
                        {
                            CheckBox cbManufacturerInfo = row.FindControl("cbManufacturerInfo") as CheckBox;
                            HiddenField hfManufacturerID = row.FindControl("hfManufacturerID") as HiddenField;
                            HiddenField hfProductManufacturerID = row.FindControl("hfProductManufacturerID") as HiddenField;
                            CheckBox cbFeatured = row.FindControl("cbFeatured") as CheckBox;
                            NumericTextBox txtRowDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox;
                            int productManufacturerID = int.Parse(hfProductManufacturerID.Value);
                            int manufacturerID = int.Parse(hfManufacturerID.Value);
                            int displayOrder = txtRowDisplayOrder.Value;

                            if (productManufacturerID > 0 && !cbManufacturerInfo.Checked)
                                ProductManufacturerManager.DeleteProductManufacturer(productManufacturerID);
                            if (productManufacturerID > 0 && cbManufacturerInfo.Checked)
                                ProductManufacturerManager.UpdateProductManufacturer(productManufacturerID, product.ProductID, manufacturerID, cbFeatured.Checked, displayOrder);
                            if (productManufacturerID == 0 && cbManufacturerInfo.Checked)
                                ProductManufacturerManager.InsertProductManufacturer(product.ProductID, manufacturerID, cbFeatured.Checked, displayOrder);
                        }

                        foreach (GridViewRow row in gvRelatedProducts.Rows)
                        {
                            CheckBox cbProductInfo2 = row.FindControl("cbProductInfo2") as CheckBox;
                            HiddenField hfProductID2 = row.FindControl("hfProductID2") as HiddenField;
                            HiddenField hfRelatedProductID = row.FindControl("hfRelatedProductID") as HiddenField;
                            NumericTextBox txtRowDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox;
                            int relatedProductID = int.Parse(hfRelatedProductID.Value);
                            int productID2 = int.Parse(hfProductID2.Value);
                            int displayOrder = txtRowDisplayOrder.Value;

                            if (relatedProductID > 0 && !cbProductInfo2.Checked)
                                RelatedProductManager.DeleteRelatedProduct(relatedProductID);
                            if (relatedProductID > 0 && cbProductInfo2.Checked)
                                RelatedProductManager.UpdateRelatedProduct(relatedProductID, product.ProductID, productID2, displayOrder);
                            if (relatedProductID == 0 && cbProductInfo2.Checked)
                                RelatedProductManager.InsertRelatedProduct(product.ProductID, productID2, displayOrder);
                        }
                        Response.Redirect("ProductDetails.aspx?ProductID=" + product.ProductID);
                    }
                    else
                        Response.Redirect("Products.aspx");
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                ProductManager.MarkProductAsDeleted(this.ProductID);
                Response.Redirect("Products.aspx");
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void btnUploadProductPicture_Click(object sender, EventArgs e)
        {
            try
            {
                Product product = ProductManager.GetByProductID(this.ProductID);
                if (product != null)
                {
                    Picture picture = null;
                    HttpPostedFile productPictureFile = fuProductPicture.PostedFile;
                    if ((productPictureFile != null) && (!String.IsNullOrEmpty(productPictureFile.FileName)))
                    {
                        byte[] productPictureBinary = PictureManager.GetPictureBits(productPictureFile.InputStream, productPictureFile.ContentLength);
                        picture = PictureManager.InsertPicture(productPictureBinary, productPictureFile.ContentType, true);
                    }
                    if (picture != null)
                    {
                        ProductPicture productPicture = ProductPictureManager.InsertProductPicture(product.ProductID, picture.PictureID, txtProductPictureDisplayOrder.Value);
                    }

                    BindPictures();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void gvwImages_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "UpdateProductPicture")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = gvwImages.Rows[index];
                NumericTextBox txtProductPictureDisplayOrder = row.FindControl("txtProductPictureDisplayOrder") as NumericTextBox;
                HiddenField hfProductPictureID = row.FindControl("hfProductPictureID") as HiddenField;

                int displayOrder = txtProductPictureDisplayOrder.Value;
                int productPictureID = int.Parse(hfProductPictureID.Value);
                ProductPicture productPicture = ProductPictureManager.GetByProductPictureID(productPictureID);

                if (productPicture != null)
                    ProductPictureManager.UpdateProductPicture(productPicture.ProductPictureID,
                       productPicture.ProductID, productPicture.PictureID, displayOrder);

                BindPictures();
            }
        }

        protected void gvwImages_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ProductPicture productPicture = (ProductPicture)e.Row.DataItem;
                Image iProductPicture = e.Row.FindControl("iProductPicture") as Image;
                if (iProductPicture != null)
                    iProductPicture.ImageUrl = PictureManager.GetPictureUrl(productPicture.PictureID);

                Button btnUpdate = e.Row.FindControl("btnUpdate") as Button;
                if (btnUpdate != null)
                    btnUpdate.CommandArgument = e.Row.RowIndex.ToString();
            }
        }

        protected void gvwImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int productPictureID = (int)gvwImages.DataKeys[e.RowIndex]["ProductPictureID"];
            ProductPicture productPicture = ProductPictureManager.GetByProductPictureID(productPictureID);
            if (productPicture != null)
            {
                PictureManager.DeletePicture(productPicture.PictureID);
                ProductPictureManager.DeleteProductPicture(productPicture.ProductPictureID);
                BindPictures();
            }
        }

        public int ProductID
        {
            get
            {
                return CommonHelper.QueryStringInt("ProductID");
            }
        }

        private List<ProductCategoryMappingHelperClass> GetProductCategoryMappings(int ForParentCategoryID,
            string prefix, ProductCategoryCollection ExistingProductCategoryCollection)
        {
            CategoryCollection categoryCollection = CategoryManager.GetAllCategories(ForParentCategoryID);
            List<ProductCategoryMappingHelperClass> result = new List<ProductCategoryMappingHelperClass>();
            for (int i = 0; i < categoryCollection.Count; i++)
            {
                Category category = categoryCollection[i];
                ProductCategory existingProductCategory = ExistingProductCategoryCollection.FindProductCategory(this.ProductID, category.CategoryID);
                ProductCategoryMappingHelperClass pcm = new ProductCategoryMappingHelperClass();
                if (existingProductCategory != null)
                {
                    pcm.ProductCategoryID = existingProductCategory.ProductCategoryID;
                    pcm.IsMapped = true;
                    pcm.IsFeatured = existingProductCategory.IsFeaturedProduct;
                    pcm.DisplayOrder = existingProductCategory.DisplayOrder;
                }
                else
                {
                    pcm.DisplayOrder = 1;
                }
                pcm.CategoryID = category.CategoryID;
                pcm.CategoryInfo = prefix + category.Name;

                result.Add(pcm);
                if (CategoryManager.GetAllCategories(category.CategoryID).Count > 0)
                    result.AddRange(GetProductCategoryMappings(category.CategoryID, prefix + "--", ExistingProductCategoryCollection));
            }

            return result;
        }

        private List<ProductManufacturerMappingHelperClass> GetProductManufacturerMappings(ProductManufacturerCollection ExistingProductManufacturerCollection)
        {
            ManufacturerCollection manufacturerCollection = ManufacturerManager.GetAllManufacturers();
            List<ProductManufacturerMappingHelperClass> result = new List<ProductManufacturerMappingHelperClass>();
            for (int i = 0; i < manufacturerCollection.Count; i++)
            {
                Manufacturer manufacturer = manufacturerCollection[i];
                ProductManufacturer existingProductManufacturer = ExistingProductManufacturerCollection.FindProductManufacturer(this.ProductID, manufacturer.ManufacturerID);
                ProductManufacturerMappingHelperClass pmm = new ProductManufacturerMappingHelperClass();
                if (existingProductManufacturer != null)
                {
                    pmm.ProductManufacturerID = existingProductManufacturer.ProductManufacturerID;
                    pmm.IsMapped = true;
                    pmm.IsFeatured = existingProductManufacturer.IsFeaturedProduct;
                    pmm.DisplayOrder = existingProductManufacturer.DisplayOrder;
                }
                else
                {
                    pmm.DisplayOrder = 1;
                }
                pmm.ManufacturerID = manufacturer.ManufacturerID;
                pmm.ManufacturerInfo = manufacturer.Name;

                result.Add(pmm);
            }

            return result;
        }

        private List<RelatedProductHelperClass> GetRelatedProducts(RelatedProductCollection ExistingRelatedProductCollection)
        {
            ProductCollection productCollection = ProductManager.GetAllProducts();
            List<RelatedProductHelperClass> result = new List<RelatedProductHelperClass>();
            for (int i = 0; i < productCollection.Count; i++)
            {
                Product product = productCollection[i];
                RelatedProduct existingRelatedProduct = ExistingRelatedProductCollection.FindRelatedProduct(this.ProductID, product.ProductID);
                RelatedProductHelperClass rp = new RelatedProductHelperClass();
                if (existingRelatedProduct != null)
                {
                    rp.RelatedProductID = existingRelatedProduct.RelatedProductID;
                    rp.IsMapped = true;
                    rp.DisplayOrder = existingRelatedProduct.DisplayOrder;
                }
                else
                {
                    rp.DisplayOrder = 1;
                }
                rp.ProductID2 = product.ProductID;
                rp.ProductInfo2 = product.Name;

                result.Add(rp);
            }

            return result;
        }

        private class ProductCategoryMappingHelperClass
        {
            public int ProductCategoryID { get; set; }
            public int CategoryID { get; set; }
            public string CategoryInfo { get; set; }
            public bool IsMapped { get; set; }
            public bool IsFeatured { get; set; }
            public int DisplayOrder { get; set; }
        }

        private class ProductManufacturerMappingHelperClass
        {
            public int ProductManufacturerID { get; set; }
            public int ManufacturerID { get; set; }
            public string ManufacturerInfo { get; set; }
            public bool IsMapped { get; set; }
            public bool IsFeatured { get; set; }
            public int DisplayOrder { get; set; }
        }

        private class RelatedProductHelperClass
        {
            public int RelatedProductID { get; set; }
            public int ProductID2 { get; set; }
            public string ProductInfo2 { get; set; }
            public bool IsMapped { get; set; }
            public int DisplayOrder { get; set; }
        }
    }
}